<?php

/**
 * SBaseController class file.
 *
 * @author Spyros Soldatos <spyros@valor.gr>
 * @link http://code.google.com/p/srbac/
 */


class BaseController extends Controller {
	
	//布局文件
	public $layout='//layouts/manage';
		
	//模块URL前缀
	protected $pre_module_url;
	
	//活动的方法名称
	public $active_action;
	
	 public function init(){
	 	$modurl = $this->module !== null ? "/".$this->module->id:"";
	 	$this->pre_module_url = $modurl;
	 }
	
	  /**
	   * Checks if srbac access is granted for the current user
	   * @param String $action . The current action
	   * @return boolean true if access is granted else false
	   */
	  protected function beforeAction($action) {
		  	//载入模块分隔符
		    $del = '-';
		
		    //取得前模块名称
		    $mod = $this->module !== null ? $this->module->id . $del : "";
		    
		    $contrArr = explode("/", $this->id);
		    $contrArr[sizeof($contrArr) - 1] = ucfirst($contrArr[sizeof($contrArr) - 1]);
		    $controller = implode(".", $contrArr);
		
		    $controller = str_replace("/", ".", $this->id);
		    // 生成静态页面 模块+分隔符+控制器（首字母大写）+方法（首字母大写）例： model-ControllerAction
		    if(sizeof($contrArr)==1){
		      $controller = ucfirst(strtolower($controller));
		    }
		    $access = $mod . $controller . ucfirst(strtolower($this->action->id));
		    
		    //验证访问页面地址是否在总是允许列表里面，是返回有权限
		    if (in_array($access, $this->allowedAccess())) {
		      return true;
		    }
		   
		    //超级管理员，无需校验权限
		    if(Yii::app()->user->getName()==F::superadminer()){
		    	return true;
		    }
		    
		    //平台超级管理员，无需校验权限
		    if(Yii::app()->user->getName()==F::setting('administrator')){
		    	return true;
		    }
		   
		    //验证SRBAC有无开启，没在开启，返回的权限访问
		    if (Yii::app()->params->srbac_debug) {
		      return true;
		    }

		    // 权限验证
		    if (!$this->checkAccess($access) || Yii::app()->user->isGuest) {
		    	$this->onUnauthorizedAccess();
		    } else {
		    	return true;
		    }
	  }
	
	  /**
	   * The auth items that access is always  allowed. Configured in srbac module's
	   * configuration
	   * @return The always allowed auth items
	   */
	  protected function allowedAccess() {
	    return AdmGroup::model()->getAllowedAccess();
	  }
	
	  protected function onUnauthorizedAccess() {
	    /**
	     *  Check if the unautorizedacces is a result of the user no longer being logged in.
	     *  If so, redirect the user to the login page and after login return the user to the page they tried to open.
	     *  If not, show the unautorizedacces message.
	     */
	    if (Yii::app()->user->isGuest) {
	      Yii::app()->user->loginRequired();
	    } else {
	      $mod = $this->module !== null ? $this->module->id : "";
	      $access = $mod . ucfirst($this->id) . ucfirst($this->action->id);
	      $error["code"] = "403";
	      $error["title"] = Yii::t('srbac', 'You are not authorized for this action');
	      $error["message"] = Yii::t('srbac', 'Error while trying to access') . ' ' . $mod . "/" . $this->id . "/" . $this->action->id . ".";
	      //You may change the view for unauthorized access
	      if (Yii::app()->request->isAjaxRequest) {
	      	
	        $this->renderPartial(Yii::app()->params->srbac_notAuthorizedView, array("error" => $error));
	      } else {
	        $this->render(Yii::app()->params->srbac_notAuthorizedView, array("error" => $error));
	      }
	      return false;
	    }
	  }
	  
	  /**
	   * 权限控制，取代原来的权限效验
	   */
	  protected function checkAccess($item){
	  		//获取当前的会员的角色
	  		$role = AdmGlog::model()->findAllByAttributes(array('userid'=>Yii::app()->user->getId()));
	  		foreach($role as $val){
	  			//除了角色可以赋给会员外，也可以直接赋值操作给会员，先验证操作权限
	  			if($val->itemname==$item){
	  				$this->addLog($item);
	  				return true;
	  			}
	  			//查找角色对应的权限
	  			$actions = $this->getRoleAction($val->itemname);
	  			//先验证操作权限
	  		  	if(!empty($actions)){foreach($actions as $val){
		  			//			if(Yii::app()->getAuthManager()->executeBizRule($val->name,$val->bizrule,$val->data))
		  			//				return true;
		  			if($val->name==$item){
		  				$this->addLog($item);
		  				return true;
		  			}
		  		}}
	  		}
	  		
	  }
	  
	  /**
	   * 获取角色对应的权限
	   */
	  protected function getRoleAction($roleid){
		  	$data = Yii::app()->filecache->get('adm_role_action');//获取缓存
		  	if(!empty($data)){
		  		if(array_key_exists($roleid,$data))
		  			return $data[$roleid];
		  	}
	  		$actions = AdmPrivilege::model()->findAllByAttributes(array('parent'=>$roleid));
	  		if(!empty($actions)){
		  		foreach($actions as $val){
		  			$roleaction[] = $val->action;
		  		}
		  		$data[$roleid] = $roleaction;
		  		Yii::app()->filecache->set('adm_role_action',$data,3600*24*30);
				return $roleaction;
	  		}else{
	  			return;
	  		}
	  }
	  
	  /**
	   * 操作记录
	   */
	  public function addLog($itme){
	  	
		  	$model = new Log();
		  	$model->zm_id = Yii::app()->user->getId();
		  	$model->zlo_name = $itme;
		  	$model->zlo_cmp_id = 0;
		  	$model->inputtime = time();
		  	$model->save();
		  	return;
	  }

}

